package com.project.shiro;

import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    public CustomRealm(){
        //创建凭证匹配器
        HashedCredentialsMatcher matcher=new HashedCredentialsMatcher();
        //设置加密算法
        matcher.setHashAlgorithmName("md5");
        //设置散列次数
        matcher.setHashIterations(1024);
        //设置加密编码，真 ---- 用Hex  假---- Base64编码
        matcher.setStoredCredentialsHexEncoded(true);
        //将realm设置凭证管理器
        this.setCredentialsMatcher(matcher);

        //开启缓存管理
        this.setCacheManager(new MemoryConstrainedCacheManager());
        //开启全局缓存
        this.setCachingEnabled(true);
        //开启认证缓存
        this.setAuthenticationCachingEnabled(true);
        //开启授权缓存
        this.setAuthorizationCachingEnabled(true);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //得到登陆用户
        UserBean user=(UserBean) principalCollection.getPrimaryPrincipal();
        //创建授权对象
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        user.getRoleList().forEach(e->{
            info.addRole(e.getName());
        });
        user.getPermissionList().forEach(e->{
            info.addStringPermission(e.getContent());
        });

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //得到用户名
        String userName=authenticationToken.getPrincipal().toString();
        //按用户名查找用户
        UserBean user=userService.findByName(userName);
        if (user!=null && "在职".equals(user.getStatus())){
            return new SimpleAuthenticationInfo(user,user.getPwd(), ByteSource.Util.bytes(user.getSalt().getBytes()),this.getName());
        }
        return null;
    }
}
